package com.ruike.controller;

import com.ruike.pojo.Admin;
import com.ruike.pojo.Student;
import com.ruike.pojo.Super;
import com.ruike.pojo.Teacher;
import com.ruike.service.AdminService;
import com.ruike.service.StudentService;
import com.ruike.service.TeacherService;
import com.ruike.utils.MD5Utils;
import com.ruike.utils.MapControl;
import com.ruike.utils.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author 吴泽胜
 * @FileName LoginController
 * @date 2021-01-07 5:59 下午
 * @Software: IntelliJ IDEA
 */
@Controller
public class LoginController {

    @Autowired(required = false)
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private AdminService adminService;

    // 登陆
    @RequestMapping(value = "/loginDo", method = RequestMethod.POST)
    public Object Login(@RequestParam("username") String username ,
                        @RequestParam("password") String password ,
                        @RequestParam(value = "rememberMe",defaultValue = "false") boolean rememberMe,
                        Model model,
                        HttpSession session ) throws Exception {
        /**
         * 使用Shiro编写认证操作
         */
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,rememberMe);

        //3.执行登录方法
        try {
            subject.login(token);

            /**
             * 身份识别
             */
            if ( subject.getPrincipals() instanceof Student ){  // 学生
                // 返回对象
                session.setAttribute("user",subject.getPrincipals());
                session.setAttribute("NickName", ((Student) subject.getPrincipals()).getNickName());
                // 返回类型
                session.setAttribute("userType","Student");
            }else if ( subject.getPrincipals() instanceof Teacher ){   // 老师
                // 返回对象
                session.setAttribute("user",subject.getPrincipals());
                session.setAttribute("NickName", ((Teacher) subject.getPrincipals()).getNickName());
                // 返回类型
                session.setAttribute("userType","Teacher");
            }else if ( subject.getPrincipals() instanceof Admin ){    // 教务处管理员
                session.setAttribute("user", subject.getPrincipals());
                session.setAttribute("NickName", ((Admin) subject.getPrincipals()).getNickName());
                // 返回类型
                session.setAttribute("userType","Admin");
            }else if ( subject.getPrincipals() instanceof Super ) {    // 系统管理员
                session.setAttribute("user", subject.getPrincipals());
                session.setAttribute("NickName", ((Super) subject.getPrincipals()).getNickName());
                // 返回类型
                session.setAttribute("userType","Super");
            }
            if ( subject.getPrincipals().getPrimaryPrincipal() instanceof Admin ){
                System.out.println( " admin ");
            }
            session.setAttribute("user", subject.getPrincipals());
            session.setAttribute("NickName", "吴泽胜");
            // 返回类型
            session.setAttribute("userType","Admin");
            //  登录成功,页面跳转
            return "redirect:/success.html";

        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "* 用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "* 密码错误");
            return "login";
        }catch( LockedAccountException e){
            model.addAttribute("msg", "* 账户已锁定");
            return "login";
        }catch ( ExcessiveAttemptsException e) {
            model.addAttribute("msg", "* 用户名或密码错误次数过多！");
            return "login";
        }catch (Exception e){
            System.out.println( e );
            model.addAttribute("msg", "* 系统错误，请联系管理员！");
            return "login";
        }finally {

        }

    }


    // 登陆
    @RequestMapping(value = "/loginDo1", method = RequestMethod.POST)
    public Object Login1(@RequestParam("username") String username ,
                         @RequestParam("password") String password ,
                         HttpSession session,
                         Model model) throws Exception {

        /**
         * 老师登陆
         */
        if ( username.length() == 8 ){
            Teacher teacher = SpringContextUtil.getBean(Teacher.class);
            teacher.setTeacher_id( username );
            teacher.setPassword( MD5Utils.getMD5( password ) );
            teacher = teacherService.findTeacherByteacherIdAndPassword(teacher);
            if (teacher != null ){
                // 返回对象
                session.setAttribute("user",teacher);
                session.setAttribute("NickName",teacher.getNickName());
                // 返回类型
                session.setAttribute("userType","Teacher");
                return "redirect:/success.html";
            }
            else {
                return MapControl.getInstance().fail().loginFail();
            }
        }
        /**
         * 学生登录
         */
        if( username.length() == 13 ){
            Student student = SpringContextUtil.getBean(Student.class);
            student.setStudent_id( username );
            student.setPassword( MD5Utils.getMD5( password ));
            student = studentService.findStudentByStudent_idAndPassword(student);
            if (student != null){
                // 返回对象
                session.setAttribute("user",student);
                session.setAttribute("NickName",student.getNickName());
                // 返回类型
                session.setAttribute("userType","Student");
                return "redirect:/success.html";
            }
        }

        /**
         * 教务处管理员登陆
         */
        if( username.length() == 11 ){
            Admin admin = SpringContextUtil.getBean(Admin.class);
            admin.setAdmin_id( username );
            admin.setPassword( MD5Utils.getMD5( password ));
            admin = adminService.findAdminByteacherIdAndPassword( admin );
            if ( admin != null ){
                // 返回对象
                session.setAttribute("user", admin);
                session.setAttribute("NickName",admin.getNickName());
                // 返回类型
                session.setAttribute("userType","Admin");
                return "redirect:/success.html";
            }
            else {
                return MapControl.getInstance().fail().loginFail();
            }
        }
        return "login";
    }

    // 注销
    @GetMapping(value = "/logout")
    public String userLoginOut(HttpSession session){
        session.invalidate();
        return "redirect:/logout";
    }
}